package service.impl;

import dao.GoodsDao;
import dao.OrderDao;
import dao.impl.GoodsDaoImpl;
import dao.impl.OrderDaoImpl;
import model.bo.OrderQueryBO;
import model.InnerResult;
import model.bo.SpecBO;
import model.enumeration.ChangeOrderState;
import model.po.Order;
import model.po.Spec;
import model.vo.ChangeOrderVO;
import model.vo.OrderVO;
import model.vo.OrdersVO;
import service.OrderService;
import utils.ModelUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    public InnerResult deleteOrder(String id) {
        int result = orderDao.deleteOrder(Integer.valueOf(id));
        return 0 == result ? InnerResult.reject("删除失败") : InnerResult.fulfill();
    }

    @Override
    public InnerResult ordersByPage(OrderQueryBO bo) {
        int total = orderDao.getTotal(bo);
        List<OrderVO> orders = orderDao.orderVOsByPage(bo);
        return InnerResult.fulfill(new OrdersVO(total, orders));
    }

    @Override
    public InnerResult order(String id) {
        Order order = orderDao.orderById(Integer.valueOf(id));
        List<Spec> specList = goodsDao.getSpecs(order.getGoodsId());
        List<SpecBO> specs = new ArrayList<>(specList.size());
        specList.forEach(spec -> {
            SpecBO tmp = new SpecBO();
            ModelUtils.copyProperties(tmp, spec, Arrays.asList("id", "specName", "unitPrice"), SpecBO.MAPTO);
            specs.add(tmp);
        });
        ChangeOrderVO vo = new ChangeOrderVO(order.getId(), order.getAmount(), order.getNumber(), order.getSpecId(), order.getState(), order.getGoods(), specs, ChangeOrderState.stateList, new ChangeOrderVO.CurState(order.getState()), new ChangeOrderVO.CurSpec(order.getSpecId()));
        return InnerResult.fulfill(vo);
    }
}
